package com.decent.text.pdf.test3;

import com.itextpdf.text.pdf.BaseFont;
import org.springframework.stereotype.Service;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author 王雪杰
 * @date 2021/11/13 14:52
 */
@Service
public class ExportPDF {

    public void exportPdf(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OutputStream os = null;
        String htmlStr;
        Map params = new HashMap<String, Object>();
        Map data = new HashMap<String, Object>(2);
        try {
            /**
             xxx数据生成逻辑
             **/
            data.put("name", "asdfzxcv");

            //通过freemaker模板生成html
            htmlStr = HtmlGenerator.generate("new测试pdf.ftl", data);
            System.out.println(htmlStr);
            String appPath = "D:\\idea\\workspace\\test-4-7\\src\\main\\resources\\pdfTest" + File.separator;
            ITextRenderer renderer = new ITextRenderer();
            renderer.setDocumentFromString(htmlStr, appPath);

            // 解决中文支持问题
            ITextFontResolver fontResolver = renderer.getFontResolver();
            fontResolver.addFont("C:/Windows/Fonts/Arial.TTF",
                    BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //生成pdf文件
            SimpleDateFormat simp = new SimpleDateFormat("HH:mm:dd");
            String times = simp.format(new Date()).trim();
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode("测试", "UTF-8") + times + ".pdf");
            response.setContentType("application/pdf");
            os = response.getOutputStream();
            renderer.layout();
            renderer.createPDF(os, true);

            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
